package com.miya.demo.support.netty.client;

import com.miya.demo.support.netty.MessageBean;
import com.miya.demo.support.netty.config.NettyProperties;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 客户端启动类
 *
 * @author CaiXiaowei
 * @date 2023/1/17
 */
@Slf4j
@RequiredArgsConstructor
public class ClientBoot {

    @NonNull
    private Bootstrap bootstrap;
    @NonNull
    private NettyProperties nettyProperties;

    /**
     * 主端口连接
     * @return
     * @throws InterruptedException
     */
    public Channel connect() throws InterruptedException {
        // 连接服务器
        ChannelFuture channelFuture = bootstrap.connect(nettyProperties.getHost(), nettyProperties.getPort()).sync();
        // 监听关闭
        Channel channel = channelFuture.channel();
        return channel;
    }
    /**
     * 备用端口连接
     * @return
     * @throws InterruptedException
     */
//    public Channel connectSlave() throws InterruptedException {
//        // 连接服务器
//        ChannelFuture channelFuture = bootstrap.connect(nettyProperties.getHost(), nettyProperties.getPort()).sync();
//        // 监听关闭
//        Channel channel = channelFuture.channel();
//        channel.closeFuture().sync();
//        return channel;
//    }

    /**
     * 发送消息到服务器端
     * @return
     */
    public void sendMsg(MessageBean messageBean) throws InterruptedException {
        connect().writeAndFlush(messageBean);
    }

}
